<?php
function getAvailableID()
{
    $availableID = 0;
    $idString = "";

    $dirHandle = opendir("../textfiles/");
    $filesArray = array();
    while (false !== ($file = readdir($dirHandle))) 
    {
        if (strstr($file, '.txt')) 
        {
            // Add each file to array
            $filesArray[] = $file;
        }
    }
    $counter = 0;
    foreach ($filesArray as $file)
    {
        // Read contents and explode ( \n then |) to $splitContents then $items
        $filename = "../textfiles/" . $file;
        $fd = fopen ($filename, "r");
        $contents = fread ($fd,filesize($filename));
        fclose ($fd);
        $splitcontents = explode("\n", $contents);
         
        foreach ($splitcontents as $value) 
        {
            $items[$counter] = explode("|", $value);
            $idString .= $items[$counter][0] . "|";
            $counter++;
        }
    }
    $usedIDs = explode("|", $idString);
      
    foreach ($usedIDs as $value)
    {
        if(in_array($availableID, $usedIDs))
        {
            $availableID ++;
        }
        else
        {
            // Found a free ID, stop searching, return it.
            return $availableID;
        }
    }
    //Must not be a free ID, $availableID is now one greater than the highest existing.
    return $availableID;
}
?> 
